import os, sys

parent_path = os.path.abspath(os.path.join(__file__, *(['..'] * 4)))
sys.path.insert(0, parent_path)

import traceback
import numpy as np
import socket, json, cv2
from typing import *
from task.modules.processors.base_processor import BaseProcessor

class TcpPush(BaseProcessor):
    def __init__(self, keys, timeout = 10) -> None:
        self.status = 0
        self.keys = keys
        self.url = None
        self.client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.client.settimeout(timeout)

    def task_init(self, data:Dict):
        self.url = data[self.keys["url"]]
        self.connect(ip = self.url.split(":")[0], port=int(self.url.split(":")[1]))
        self.status = 1

    def connect(self, ip, port):
        self.client.connect((ip,port))

    def __call__(self, data:Dict) -> Dict:
        result = data[self.keys["in"]]
        result = {"data":result,
                  "shape":data["input_data"].shape}
        result_seq = json.dumps(result)
        try:
            self.client.send(result_seq.encode())
        except:
            print(traceback.format_exc())
            assert self.status != 0
            self.connect(ip = self.url.split(":")[0], port=int(self.url.split(":")[1]))
        return data

    def close(self):
        if self.status !=0:
            self.status = 0
            self.client.close()

if __name__ == "__main__":
    tcp_pusher = TcpPush(keys={
        "in":"ocr",
        "url":"url",
    })
    data = {
        "url":"192.168.101.174:2692"
    }
    tcp_pusher.set(data=data)
    print("")
